package com.site.user.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import com.site.data.JPABaseDAOImpl;
import com.site.user.pojo.TbGroup;
import com.site.user.pojo.TbRole;
import com.site.user.pojo.TbUser;

/**
 * @author      zhanjun
 * @date        2010-12-8
 * @version     1.0
 * @description 用户表服务层
 * 
 */
@Service("tbUserService")
public class TbUserService extends JPABaseDAOImpl<TbUser> implements ITbUserService {

	@Override
	public String getUserPrivilege(TbUser instance, String systemid) {// 得到用户权限树

		String utype = instance.getSign();
		String treesql = "";
		String orderby = "  order by vp.ID_RESOURCE, vp.ORDERBY";
		if ("99".equals(utype)) {// 超级用户
			treesql = "select distinct vp.ID_RESOURCE,vp.PARENT_ID,vp.RES_NAME,vp.RESOURCE,vp.RES_DESC from TB_RESOURCE vp  where 1=1";
			if (!systemid.equals("")) {
				treesql += " and vp.ID_RESOURCE=" + systemid + " or vp.SYSTEM=" + systemid;
			}

		} else {
			Object[] rid = getUserRolesId(instance);
			String rolesid = "'" + StringUtils.join(rid, "','") + "'";
			treesql = "select distinct vp.ID_RESOURCE,vp.PARENT_ID,vp.RES_NAME,vp.RESOURCE,vp.RES_DESC"
					+ " from V_PRIVIGE vp where vp.ID_ROLE in (" + rolesid + ")";
			if (!systemid.equals("")) {
				treesql += " and vp.ID_SYSTEM=" + systemid;
			}

		}
		treesql += orderby;
		

		List<Object[]> listsys = null;
		listsys = jdbcExecQuery(treesql, null);
		StringBuilder sb = new StringBuilder();
		int listsize = listsys.size();
		sb.append("[");
		for (int i = 0; i < listsys.size(); i++) {
			Object[] obj = listsys.get(i);
			sb.append("{");
			sb.append("\"id\":\"" + obj[0] + "\"");
			sb.append(",");
			sb.append("\"pId\":\"" + obj[1] + "\"");
			sb.append(",");
			sb.append("\"name\":\"" + obj[2] + "\"");
			sb.append(",");
			sb.append("\"resource\":\"" + obj[3] + "\"");
			sb.append(",");
			sb.append("\"resDesc\":\"" + obj[4] + "\"");
			sb.append("}");
			if (i != listsize - 1) {
				sb.append(",");
			}
		}
		sb.append("]");
		return sb.toString();

	}

	/**
	 * 得到用戶的角色id
	 * @param entity
	 * @return
	 */
	@Override
	public Object[] getUserRolesId(TbUser entity) {
		Set<TbRole> roles = entity.getTbRoleSet();
		Set<TbGroup> groups = entity.getTbGroupSet();

		Set<String> rolesId = new HashSet<String>();
		if (roles != null) {
			for (TbRole r : roles) {
				rolesId.add(r.getIdRole());
			}
		}
		if (groups != null) {
			for (TbGroup g : groups) {
				Set<TbRole> grole = g.getTbRoleSet();
				if (grole != null) {
					for (TbRole r : grole) {
						rolesId.add(r.getIdRole());
					}
				}
			}
		}
		return rolesId.toArray();
	}

	/**
	 * 得到用戶的組id
	 * @param entity
	 * @return
	 */
	@Override
	public String[] getUserTbGroupId(TbUser entity) {

		Set<TbGroup> groups = entity.getTbGroupSet();

		Set<String> rolesId = new HashSet<String>();

		if (groups != null) {
			for (TbGroup g : groups) {
				rolesId.add(g.getIdGroup());
			}
		}

		return (String[]) rolesId.toArray();
	}

	/* (non-Javadoc)
	 * @see com.site.user.service.ITbUserService#userRoleSave(java.lang.String, java.lang.String)
	 */
	@Override
	public String userRoleSave(String idUser, String idRole) {
		String msg = "ERROR";
		if ((StringUtils.isNotEmpty(idUser)) && (StringUtils.isNotEmpty(idRole))) {

			String[] roles = null;

			if (StringUtils.isNotEmpty(idRole)) {

				if (idRole.indexOf(",") != -1) {
					roles = idRole.split(",");
				} else {
					roles = new String[] { idRole };
				}
			} else {
				return null;
			}

			String[] users = null;

			if (StringUtils.isNotEmpty(idUser)) {
				if (idUser.indexOf(",") != -1) {
					users = idUser.split(",");
				} else {
					users = new String[] { idUser };
				}
			} else {
				return null;
			}

			/*
			 * 先删除原有角色对象
			 */
			String delsql = "delete from tb_user_role where ID_USER='" + idUser + "'";
			jdbcExecUpdate(delsql);

			String insert = "INSERT INTO tb_user_role (ID_USER,ID_ROLE) VALUES";
			List<String> sqlvalue = new ArrayList<String>();
			StringBuilder sql = null;

			for (int j = 0; j < users.length; j++) {
				for (int i = 0; i < roles.length; i++) {
					String roleid = roles[i];
					String userid = users[j];
					sql = new StringBuilder();
					sql.append("(");
					sql.append("'");
					sql.append(userid);
					sql.append("','");
					sql.append(roleid);
					sql.append("'");
					sql.append(")");
					sqlvalue.add(sql.toString());
				}
			}

			if (sqlvalue.size() > 0) {
				String insql = insert + StringUtils.join(sqlvalue, ",");
				jdbcExecUpdate(insql);
				msg = "保存成功";
			}
		}
		return msg;
	}

	@Override
	public String userGroupSave(String idUser, String idGroup) {
		String msg = "ERROR";
		if ((StringUtils.isNotEmpty(idUser)) && (StringUtils.isNotEmpty(idGroup))) {

			String[] groups = null;

			if (StringUtils.isNotEmpty(idGroup)) {

				if (StringUtils.indexOf(idGroup, ",")!= -1) {
					groups = StringUtils.split(idGroup);
				} else {
					groups = new String[] { idGroup };
				}
			} else {
				return null;
			}

			String[] users = null;

			if (StringUtils.isNotEmpty(idUser)) {
				
				if (StringUtils.indexOf(idUser, ",")!= -1) {
					users = StringUtils.split(idUser);
				} else {
					users = new String[] { idUser };
				}
				
			} else {
				return null;
			}

			/*
			 * 先删除原有角色对象
			 */
			String delsql = "delete from tb_user_group where ID_USER='" + idUser + "'";
			jdbcExecUpdate(delsql);

			String insert = "INSERT INTO tb_user_group (ID_USER,ID_GROUP) VALUES";
			List<String> sqlvalue = new ArrayList<String>();
			StringBuilder sql = null;

			for (int j = 0; j < users.length; j++) {
				for (int i = 0; i < groups.length; i++) {
					String gid = groups[i];
					String userid = users[j];
					sql = new StringBuilder();
					sql.append("(");
					sql.append("'");
					sql.append(userid);
					sql.append("','");
					sql.append(gid);
					sql.append("'");
					sql.append(")");
					sqlvalue.add(sql.toString());
				}
			}

			if (sqlvalue.size() > 0) {
				String insql = insert + StringUtils.join(sqlvalue, ",");
				jdbcExecUpdate(insql);
				msg = "保存成功";
			}
		}
		return msg;
	}

	@Override
	public String delUserRole(String idUser, String idRole) {
		/*
		 * 先删除原有角色对象
		 */
		String delsql = "delete from tb_user_role where ID_USER='" + idUser + "' and ID_ROLE='"+idRole+"'";		
		jdbcExecUpdate(delsql);
		String msg = "删除成功";
		return msg;

	}
	@Override
	public String delUserGroup(String idUser, String idGroup) {
		/*
		 * 先删除原有组对象
		 */
		String delsql = "delete from tb_user_group where ID_USER='" + idUser + "' and ID_Group='"+idGroup+"'";		
		jdbcExecUpdate(delsql);
		String msg = "删除成功";
		return msg;
	}
	
}
